package com.mlk.engUser.task;

import cn.hutool.core.util.XmlUtil;
import com.mlk.constant.EngConstant;
import com.mlk.core.exception.GlobalException;
import com.mlk.engUser.mapper.EngUserMapper;
import com.mlk.engUser.mapper.EngUserOutRemainMapper;
import com.mlk.engUser.mapper.EngUserRemainVerifyMapper;
import com.mlk.engUser.po.EngUserOutRemain;
import com.mlk.engUser.po.EngUserRemainVerify;
import com.mlk.engUser.tonglian.AIPGException;
import com.mlk.engUser.tonglian.DemoConfig;
import com.mlk.engUser.tonglian.util.DemoUtil;
import com.mlk.engUser.tonglian.util.HttpUtil;
import com.mlk.engUser.tonglian.xml.XmlParser;
import com.mlk.engUser.tonglian.xstruct.common.AipgReq;
import com.mlk.engUser.tonglian.xstruct.common.InfoReq;
import com.mlk.engUser.tonglian.xstruct.trans.qry.TransQueryReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 通联的交易查询
 */
@Component
@Slf4j
public class TonglianTask {

    @Resource
    private EngUserRemainVerifyMapper engUserRmainVerifyMapper;
    @Resource
    private EngUserMapper engUserMapper;

    @Resource
    private EngUserOutRemainMapper engUserOutRemainMapper;
    /**
     * 每三分钟调度一下任务,发现初始化的交易,然后进行处理
     */
    // 0 0/1 * * * ?
    @Scheduled(fixedRate = 3 * 60 * 1000)
    public void task() {
        log.info("支付查询任务调度开始");
        List<EngUserRemainVerify> lists = this.engUserRmainVerifyMapper.selectAwaitVrify();

        lists.stream().forEach(element -> {
            log.info("通联任务调度===>",element.toString());
            Date createTime = element.getCreateTime();
            // 当前时间比创建时间之后的三十分钟还大的话,就说明已经超时了.
            if (DateUtils.addMinutes(createTime, 30).getTime() < new Date().getTime()) {
                Integer id = element.getId();
                // 更新超时
                this.engUserRmainVerifyMapper.updateById(EngUserRemainVerify.builder().id(id).status(3).
                        remark("超时未受理").build());
            }


            // 下面调用接口查询是否是0000
            String resXml = handleVerify(element.getSn());
            String retCode = XmlUtil.parseXml(resXml).getElementsByTagName("RET_CODE").item(0).getTextContent();
            if ("0000".equals(retCode)) {
                Map<String, Object> map = XmlUtil.xmlToMap(XmlUtil.parseXml(resXml).getElementsByTagName("QTDETAIL").item(0));
                retCode = String.valueOf(map.get("RET_CODE"));
                String errmsg = String.valueOf(map.get("ERR_MSG"));
                // 根据状态值更新内容
                int status = 2;
                if(!StringUtils.equals("0000",retCode)){
                    status = 3;
                }
                EngUserRemainVerify verify = new EngUserRemainVerify();
                verify.setId(element.getId());
                verify.setStatus(status);
                verify.setRemark(errmsg);
                this.engUserRmainVerifyMapper.updateById(verify);
                // 下面进行业务的处理

                // 将客户的余额减去
                int count = this.engUserMapper.addRemain(element.getOpenId(),element.getAmount().negate());
                if(count == 0){
                    throw new GlobalException("操作失败");
                }

                // 填写余额减少的记录
                EngUserOutRemain outRemain = new EngUserOutRemain ();
                outRemain.setOpenId(element.getOpenId());
                outRemain.setCreateTime(new Date());
                outRemain.setAmount(element.getAmount());
                outRemain.setType(EngConstant.OUT_REMAIN_TARGET.OUT_REMAIN);
                this.engUserOutRemainMapper.insert(outRemain);
            }
        });
    }

    /**
     * 调用通联支付,获取响应
     *
     * @param sn
     * @return
     */
    public String handleVerify(String sn) {
        InfoReq infoReq = DemoUtil.makeReq("200004");
        TransQueryReq queryReq = new TransQueryReq();
        queryReq.setMERCHANT_ID(DemoConfig.merchantid);
        // 200604000007235-0001567128103110
        queryReq.setQUERY_SN(sn);///查询交易的文件名
		/*queryReq.setSTART_DAY("");
		queryReq.setEND_DAY("");*/
        AipgReq req = new AipgReq();
        req.setINFO(infoReq);
        req.addTrx(queryReq);

        try {
            //step1 对象转xml
            String xml = XmlParser.toXml(req);
            //step2 加签
            String signedXml = DemoUtil.buildSignedXml(xml);
            //step3 发往通联
            String url = DemoConfig.url + "?MERCHANT_ID=" + DemoConfig.merchantid + "&REQ_SN=" + infoReq.getREQ_SN();
            System.out.println("============================请求报文============================");
            System.out.println(signedXml);
            String respText = HttpUtil.post(signedXml, url);
            System.out.println("============================响应报文============================");
            System.out.println(respText);
            //step4 验签
            if (!DemoUtil.verifyXml(respText)) {
                System.out.println("====================================================>验签失败");

            }
            System.out.println("====================================================>验签成功");
            //step5 xml转对象
            return  respText;

        } catch (AIPGException e) {
            e.printStackTrace();
        }
        return null;
    }

}